<template>
  <div style="height: 600px;width: 100%;">
<!--    <div style="height: 100px;width: 100%;">-->
<!--    &lt;!&ndash; 面包屑导航 &ndash;&gt;-->
<!--    <el-breadcrumb separator-class="el-icon-arrow-right">-->
<!--      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>-->
<!--      <el-breadcrumb-item>机器人添加编辑</el-breadcrumb-item>-->
<!--    </el-breadcrumb>-->
<!--    </div>-->
    <div style="height: 400px;width: 100%;">
      <div style="height: 80%;width: 40%;float: left">
        <div style="height: 10%;text-align: center;"></div>

        <div style="height: 20%;text-align: center;">{{title}}</div>

        <el-form label-width="120px" :model="DataForm" ref="DataForm" :rules="rules">
          <el-form-item label="主键" prop="id" v-show="false">
            <el-input size="small" v-model="DataForm.id" auto-complete="off" placeholder="请输入主键"></el-input>
          </el-form-item>
          <el-form-item label="机器人名称" prop="rebotName">
            <el-input size="small" v-model="DataForm.rebotName" auto-complete="off" placeholder="请输入机器人名称"></el-input>
          </el-form-item>
          <el-form-item label="提示词" prop="promptWord">
            <el-input type="textarea"  :rows="4"  v-model="DataForm.promptWord" auto-complete="off" >
            </el-input>
            <span style="color: #da0736; margin-left: 8px;display: block;">x代表您输入的问题</span>
            <span style="color: #da0736; margin-left: 8px;display: block;">y代表文档中根据问题找到的答案</span>
            <span style="color: #da0736; margin-left: 8px;display: block;">最后统一交给大模型做文本提取</span>
          </el-form-item>
          <el-form-item label="回答风格选项" prop="style">
            <el-radio-group v-model="DataForm.style">
              <el-radio :label="'普通风格'">普通风格</el-radio>
              <el-radio :label="'简单风格'">简单风格</el-radio>
              <el-radio :label="'严谨标准风格'">严谨标准风格</el-radio>
              <el-radio :label="'自然风格'">自然风格</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="文件（知识库）" prop="docId">
            <el-select v-model="DataForm.docId" multiple placeholder="请选择">
              <el-option
                v-for="(docName, id) in optionMap"
                :key="id"
                :label="docName"
                :value="id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="人工回复文案" prop="manualReplyContent">
            <el-input type="textarea"  :rows="3"  v-model="DataForm.manualReplyContent" auto-complete="off" >
            </el-input>
          </el-form-item>
          <el-form-item label="欢迎语" prop="welcomeMessage">
            <el-input type="textarea"  :rows="3"  v-model="DataForm.welcomeMessage" auto-complete="off" >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
            <el-button size="small" v-if="title !=='机器人体验'" type="primary" :loading="loading" class="title" @click="submitForm('DataForm')">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div style="height: 80%;width: 9%;float: left">
      </div>
      <div style="height: 80%;width: 50%;float: left">
        <el-row :gutter="20" style="height: 100%;width: 100%;float: left">
          <el-col :span="12">
            <div class="title-bar">AI问答</div>
            <div id="chat-window" class="chat-window" >
              <div id="ChatGPT-response" ref="responseText" class="chat-log" >
                <div
                  v-for="(message, index) in chatLog"
                  :key="index"
                  :class="{'user-message': message.startsWith('👤:'), 'ai-message': message.startsWith('🤖:')}"
                >
                  {{ message }}
                </div>
              </div>
            </div>
            <div id="chat-input" class="chat-input">
              <el-input
                v-model="inputText"
                id="chat-gpt-input"
                style="width: 350px"
                placeholder="输入问题"
                clearable
              ></el-input>

              <el-button :loading="loading" size="small" type="primary"  @click="callCHATGPT">发送</el-button>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import {
  ModelSave,
  getModelById,
  modelUpload, FapiaoSave, FapiaoUpdate, rebotSave, rebotUpdate, getAllCategoryList, getAllDocList, rebotApi
} from '../../api/userMG'
import imageUpload from "../../imageUpload/index.vue";

export default {
  components: {imageUpload},
  data() {
    return {
      fileList: [],
      fileContent: '',
      imageUrl:'',
      loading: false, //是显示加载
      optionMap:[],
      chatLog: [],
      title:'新增机器人',//界面
      text:'你是一个智能助手,请基于以下专业知识，回答以下问题：[x]。\n' +
        '专业知识：“相关问题:[x]。 相关答案:[y]”',
      inputText: '',
      DataForm: {
        id:'',
        rebotName:'',
        promptWord:'你是一个智能助手,请基于以下专业知识，回答以下问题：[x]。\n' +
          '专业知识：“相关问题:[x]。 相关答案:[y]”',
        docId:[],
        style:'普通风格',
        docIds:'',
        manualReplyContent:'',
        welcomeMessage:'',
        imageurl:'',
      },
      rebotContent: {
        id:'',
        prompt:'',
      },
      // rules 表单验证
      rules: {
        rebotName: [
          { required: true, message: '请输入机器人名称', trigger: 'blur' }
        ],
        promptWord: [
          { required: true, message: '请输入提示词', trigger: 'blur' }
        ],
        docId: [
          { required: true, message: '请输入文件', trigger: 'blur' }
        ],

      },
    };
  },
  created() {
    console.log(this.$route.params)
    this.DataForm.id = this.$route.params.id;
    this.DataForm.rebotName = this.$route.params.rebotName;
    this.DataForm.manualReplyContent = this.$route.params.manualReplyContent;
    this.DataForm.welcomeMessage = this.$route.params.welcomeMessage;
    if(this.$route.params.title != undefined
      && this.$route.params.title != 'undefined'){
      this.title = this.$route.params.title;
      this.DataForm.promptWord = this.$route.params.promptWord;
      if(this.DataForm.welcomeMessage!= undefined
      && this.DataForm.welcomeMessage!= "undefined"
        && this.DataForm.welcomeMessage!= ""
        && this.DataForm.welcomeMessage!= "null"
        && this.DataForm.welcomeMessage!= null){
        this.chatLog.push('🤖:'+this.DataForm.welcomeMessage);
      }else {
        this.chatLog.push('🤖: 您好，我是您的专属智能机器人，有什么可以帮助您的吗？');
      }

    }
    if(this.$route.params.docIds != undefined
      && this.$route.params.docIds != 'undefined'
      && this.$route.params.docIds != ''){
      this.DataForm.docId = this.$route.params.docIds.split(",");
    }
    console.log(this.DataForm)
  },
  mounted() {
    this.getDocList()
  },
  methods: {
    closeDialog(obj){
      this.$router.push({ name: 'rebot' });//跳转到查询界面
    },
    // 编辑、增加保存方法
    submitForm(editData) {
      this.loading = true
      this.$refs[editData].validate(valid => {
        if (valid) {
          this.DataForm.docIds = this.DataForm.docId.join(",");
          if(this.DataForm.id != undefined && this.DataForm.id != 'undefined' && this.DataForm.id != ''){
            console.log(this.DataForm.id)
            rebotUpdate(this.DataForm)
              .then(res => {
                console.log(res.success)
                if(res.code==null){
                  this.$router.push({ name: 'login' });//跳转到查询界面
                }
                if (res.code===0) {
                  // this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '数据更新成功！'
                  })
                  this.chatLog.pop()
                  if(this.DataForm.welcomeMessage!= undefined
                    && this.DataForm.welcomeMessage!= "undefined"
                    && this.DataForm.welcomeMessage!= ""
                    && this.DataForm.welcomeMessage!= "null"
                    && this.DataForm.welcomeMessage!= null){
                    this.chatLog.push('🤖:'+this.DataForm.welcomeMessage);
                  }else {
                    this.chatLog.push('🤖: 您好，我是您的专属智能机器人，有什么可以帮助您的吗？');
                  }
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.$message.error('机器人更新失败，请稍后再试！')
              })
          }else {
            rebotSave(this.DataForm)
              .then(res => {
                console.log(res.success)
                if(res.code==null){
                  this.$router.push({ name: 'login' });//跳转到查询界面
                }
                if (res.code===0) {
                  // this.getdata(this.formInline)
                  this.$message({
                    type: 'success',
                    message: '数据保存成功！'
                  })
                  this.DataForm.id = res.data;
                  if(this.DataForm.welcomeMessage!= undefined
                    && this.DataForm.welcomeMessage!= "undefined"
                    && this.DataForm.welcomeMessage!= ""
                    && this.DataForm.welcomeMessage!= "null"
                    && this.DataForm.welcomeMessage!= null){
                    this.chatLog.push('🤖:'+this.DataForm.welcomeMessage);
                  }else {
                    this.chatLog.push('🤖: 您好，我是您的专属智能机器人，有什么可以帮助您的吗？');
                  }
                } else {
                  this.$message({
                    type: 'info',
                    message: res.msg
                  })
                }
              })
              .catch(err => {
                this.$message.error('机器人保存失败，请稍后再试！')
              })
          }
        } else {
          return false
        }
      })
      this.loading = false
    },
    getDocList(){
      getAllDocList()
        .then(res => {
          this.loading = false
          console.log(res)
          if(res.code==null){
            this.$router.push({ name: 'login' });//跳转到查询界面
          }
          if (res.code!=0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.loading = false
            // 分页赋值
            const data = res.data;
            // 将数据组装成字典
            this.optionMap = data.reduce((acc, cur) => {
              acc[cur.id] = cur.docName;
              return acc;
            }, {});
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取类目列表失败，请稍后再试！')
        })
    },
    async callCHATGPT() {
      this.rebotContent.id = this.DataForm.id
      this.rebotContent.prompt = this.inputText
      this.chatLog.push('👤:' + this.inputText);
      this.inputText = '';
      rebotApi(this.rebotContent)
        .then(res => {
          console.log(res.success)
          if(res.code==null){
            this.$router.push({ name: 'login' });//跳转到查询界面
          }
          if (res.code===0) {
            // this.getdata(this.formInline)
            this.resData = res.data.response;
            console.log(this.resData)
            this.chatLog.push('🤖:' + this.resData);
            this.loading = false; // 请求失败，结束加载状态
          } else {
            this.$message({
              type: 'info',
              message: res.msg
            })
          }
        })
        .catch(err => {
          this.loading = false; // 请求失败，结束加载状态
          console.error('请求失败：', err);
          this.$message.error('请求失败，请稍后再试！');
        })
    },
    handleSuccess(res, file) {
      if(res.code==null){
        this.$router.push({ name: 'login' });//跳转到查询界面
      }
      // 上传成功后的处理逻辑
      if (res.code === 0) {
        this.DataForm.amount = res.data.amount;
        this.DataForm.billnum = res.data.billnum;
        this.DataForm.imageurl = res.data.imageurl;
        this.fileList.push({ name: res.data.imageurl, url: res.data.imageurl });
        this.imageUrl = this.baseUrl+res.data.imageurl;
        console.log(this.imageUrl)
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 删除图片
    handleDelete(file) {
      this.imageUrl=null;
      // const findex = this.fileList.map(f => f.name).indexOf(file.name);
      // if (findex > -1) {
      //   this.fileList.splice(findex, 1);
      //   this.$emit("input", this.listToString(this.fileList));
      // }
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt500k = file.size / 1024 < 500;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt500k) {
        this.$message.error('上传图片大小不能超过 500KB!');
      }
      return isJPG || isPNG && isLt500k;
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
  }
};
</script>
<style scoped>
.avatar-upload {
  width: 100px; /* 你可以根据需要调整这个值 */
  height: 100px; /* 你可以根据需要调整这个值 */
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden; /* 隐藏超出容器的内容 */
  position: relative;
  cursor: pointer;
}
.avatar-uploader {
  width: 800px; /* 你可以根据需要调整这个值 */
  height: 600px; /* 你可以根据需要调整这个值 */
  border: 1px solid #ddd;
  border-radius: 4px;
  overflow: hidden; /* 隐藏超出容器的内容 */
  position: relative;
  cursor: pointer;
}

.avatar {
  width: 800px;
  height: 600px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.image-preview {
  max-width: 800px; /* 图片最大宽度为容器宽度 */
  max-height: 600px; /* 图片最大高度为容器高度 */
  object-fit: cover; /* 保持图片比例，同时填充整个容器 */
}

.avatar-uploader-icon {
  font-size: 40px;
  color: #8c939d;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.breadcrumb{
  margin-bottom: 10px; /* 可选：添加底部外边距，以便与其他元素分隔 */
}

.title-bar {
  background-color: #1929bd; /* 蓝色背景 */
  color: white; /* 白色文字 */
  padding: 10px; /* 内边距 */
  width: 400px;
  text-align: center; /* 文字居中 */

}
.scrollable-shadow-box {
  border: 1px solid #dcdfe6; /* 边框样式 */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  padding: 25px;
}
.chat-window {
  display: flex;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  flex-direction: column-reverse; /* 显示最新的消息在最上面 */
  height: 500px; /* 可以根据需要调整 */
  width: 400px;
  overflow-y: auto; /* 超出部分滚动显示 */
  padding: 10px;
  background-color: #f5f7fa;
  border: 1px solid #ccc;
  margin-bottom: 15px;

}

.chat-log {
  display: flex;
  flex-direction: column;
  width: 100%;

}

.user-message {
  align-self: flex-end; /* 用户消息靠右 */
  margin-right: 10px;
  background-color: #53bef1;
  padding: 5px 10px;
  border-radius: 5px 5px 5px 0;
  max-width: 70%; /* 可以根据需要调整 */
  margin-bottom: 10px;
}

.ai-message {
  align-self: flex-start; /* AI消息靠左 */
  margin-left: 10px;
  background-color: #e0f2f1;
  padding: 5px 10px;
  border-radius: 5px 5px 0 5px;
  max-width: 70%; /* 可以根据需要调整 */
  margin-bottom: 10px;
}
.chat-input {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
  width: 400px;
}

.chat-input .el-input {
  flex: 1; /* 输入框占据剩余空间 */
}

.chat-input .el-button {
  margin-left: 10px; /* 与输入框保持一定距离 */
}
</style>
